﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace VOL.WebApi.CustomeMiddleWare
{
    public class IpRestrictionFilterAttribute:ActionFilterAttribute
    {
        private readonly IConfiguration _configuration;

        public IpRestrictionFilterAttribute(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            string[] allowedIpAddresses = _configuration["IpRestriction"].Split(',');
            IPAddress ipAddress = context.HttpContext.Connection.RemoteIpAddress;
            if (!IsAllowed(ipAddress, allowedIpAddresses))
            {
                context.Result = new ContentResult
                {
                    Content = "禁止： 你的IP不允许访问!",
                    StatusCode = (int)HttpStatusCode.Forbidden
                };
            }
        }

        private bool IsAllowed(IPAddress ipAddress, string[] allowedIpAddresses)
        {
            return allowedIpAddresses.Any(a => IPAddress.Parse(a).MapToIPv6().ToString().Equals(ipAddress.MapToIPv6().ToString()));
        }
    }
}
